package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@Service(timeout = 100000)
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public void save(Publish publish) {
        publish.setCreated(System.currentTimeMillis());
        //【设置pid，用于大数据推荐计算】
        publish.setPid(idService.getNextId("quanzi_publish"));
        mongoTemplate.save(publish);

        Album album = new Album();
        album.setCreated(publish.getCreated());
        album.setId(publish.getId());
        mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        if (friends != null) {

            for (Friend friend : friends) {
                Long friendId = friend.getFriendId();
                TimeLine timeLine = new TimeLine();
                timeLine.setUserId(publish.getUserId());
                timeLine.setPublishId(publish.getId());
                timeLine.setCreated(publish.getCreated());
                mongoTemplate.save(timeLine, "quanzi_time_line_" + friendId);
            }
        }
    }

    @Override
    public PageResult findByTimLine(Integer page, Integer pagesize, Long userId) {
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1) * pagesize);
        List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        long count = mongoTemplate.count(query, TimeLine.class, "quanzi_time_line_" + userId);
        List<Publish> list = new ArrayList<>();
        if (timeLines != null) {
            for (TimeLine line : timeLines) {
                if (line.getPublishId() != null) {
                    Publish p = mongoTemplate.findById(line.getPublishId(), Publish.class);
                    if (p != null) {
                        list.add(p);
                    }

                }
            }
        }
        return new PageResult(page, pagesize, (int) count, list);
    }

    @Override
    public PageResult findByRecommend(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(page).skip((page - 1) * pagesize);
        long count = mongoTemplate.count(query, RecommendQuanzi.class);
        ArrayList<Publish> publishes = new ArrayList<>();
        List<RecommendQuanzi> recommendQuanzis = mongoTemplate.find(query, RecommendQuanzi.class);
        if (recommendQuanzis != null) {
            for (RecommendQuanzi quanzi : recommendQuanzis) {
                if (quanzi.getPublishId() != null) {
                    Query q = new Query(Criteria.where("_id").is(quanzi.getPublishId()).and("state").is(1));
                    Publish pub = mongoTemplate.findOne(q,Publish.class);
                    if (pub != null) {
                        publishes.add(pub);
                    }
                }
            }

        }
        return new PageResult(page, pagesize, (int) count, publishes);
    }

    @Override
    public PageResult queryByUser(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1)*pagesize);
        List<Publish> publishes = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);
        return new PageResult(page, pagesize, (int) count, publishes);
    }

    @Override
    public Publish findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId), Publish.class);
    }

    @Override
    public PageResult queryByPage(Integer page, Integer pagesize, Long uid) {

        Query query = new Query();
        if (uid != null) {
            query = new Query(Criteria.where("userId").is(uid).and("state").is(1));
        }
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1) * pagesize);
        List<Publish> list = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);
        return new PageResult(page, pagesize, (int) count, list);

    }

    @Override
    public void updateById(String publishId, Integer state) {
        Query query = new Query(Criteria.where("_id").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state", state);
        mongoTemplate.updateFirst(query,update,Publish.class);
    }

    @Override
    public List<Publish> findByPids(ArrayList<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        List<Publish> publishes = mongoTemplate.find(query, Publish.class);
        return publishes;
    }
}

